package st.business.tepth.business.user.busnumber.workholder.maintain.finish;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.Group;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.MaintainPassInfoBean;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.business.businfo.BusInfoDelegate;
import st.business.tepth.business.event.ReloadBusNumberDataEvent;
import st.business.tepth.business.event.ReloadMaintainWorkDataEvent;
import st.business.tepth.business.event.StartBrotherEvent;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogProtocol;
import st.business.tepth.config.ItemFields;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.core.util.utilcode.util.ToastUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;
import st.shadow.library.ui.recycler.BaseDecoration;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2019/4/19
 */
public class MaintainFinishDelegate extends MvpFragment<MaintainFinishPresenter>
        implements MaintainFinishContract.View {
    public static MaintainFinishDelegate newInstance(int id,
                                                     int type,
                                                     int operationState) {
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        bundle.putInt("type", type);
        bundle.putInt("operationState", operationState);
        MaintainFinishDelegate delegate = new MaintainFinishDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.recycler_view_tab)
    RecyclerView mRecyclerViewClassification;
    @BindView(R2.id.tv_work_type)
    TextView mTvType;
    @BindView(R2.id.view_pager)
    ViewPager mViewPager;
    @BindView(R2.id.tv_check_pass)
    TextView mTvPass;
    @BindView(R2.id.tv_check_not_pass)
    TextView mTvNotPass;
    @BindView(R2.id.cb_protocol)
    CheckBox mCbProtocol;
    @BindView(R2.id.group_operation)
    Group mGroupOperation;
    @BindView(R2.id.tv_cancel_work)
    TextView mTvCancelWork;

    private ClassificationAdapter mClassificationAdapter;
    private int mType;
    private int mRepairId;
    private DialogLoader mDialogLoader;
    private int mOperationState;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("id");
            mType = bundle.getInt("type");
            mOperationState = bundle.getInt("operationState");
        }
    }

    @Override
    public MaintainFinishPresenter getPresenter() {
        return new MaintainFinishPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_maintain_work_finish;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        String type = "";
        switch (mType) {
            case 1:
                type = "小修";
                break;
            case 2:
                type = "一级保养";
                break;
            case 3:
                type = "二级保养";
                break;
            case 4:
                type = "三级保养";
                break;
            case 5:
                type = "电池保养";
                break;
        }
        mTvType.setText(String.format("%s--待竣检", type));
        if (mOperationState == 0) {
            mGroupOperation.setVisibility(View.GONE);
        } else {
            mGroupOperation.setVisibility(View.VISIBLE);
        }
        mRecyclerViewClassification.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewClassification.addItemDecoration(
                BaseDecoration.create(_mActivity.getResources()
                        .getColor(R.color.fontColorWhite), 2));
        RecyclerView.ItemAnimator itemAnimator = mRecyclerViewClassification.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
        }
        mRecyclerViewClassification.setAdapter(mClassificationAdapter =
                new ClassificationAdapter(R.layout.item_maintain_finish_classification,
                        null, new OnItemChooseListener<Integer>() {
                    @Override
                    public void onChoose(Integer position) {
                        chooseMaintain(position);
                    }
                }));
        mDialogLoader = new DialogLoader(_mActivity);
        mPresenter.getData(UserManager.getInstance().getToken(), mRepairId);
    }

    @Override
    public void showData(List<MultipleItemEntity> list) {
        mClassificationAdapter.setNewData(list);
        if (!list.isEmpty()) {
            chooseMaintain(0);
            mViewPager.setAdapter(new MaintainContentAdapter(getChildFragmentManager(),
                    list));
            //判断过检员是不是工单的作业人，如果是则按钮【取消作业完成】需要展示
            //如果不是则不需要展示该按钮
            boolean isWorker = false;
            for (MultipleItemEntity entity : list) {
                MaintainPassInfoBean infoBean = entity.getField(ItemFields.ITEM_OBJ);
                if (infoBean != null) {
                    List<PersonBean> workers = infoBean.getWorkerList();
                    if (workers != null) {
                        for (PersonBean personBean : workers) {
                            if (personBean.getJob_no().
                                    equals(UserManager.getInstance().getCurrentUserCode())) {
                                isWorker = true;
                                break;
                            }
                        }
                    }
                }
            }
            mTvCancelWork.setVisibility(isWorker ? View.VISIBLE : View.GONE);
        }
    }

    private void chooseMaintain(int position) {
        mViewPager.setCurrentItem(position);
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void checkNotPassSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                EventBus.getDefault().post(new ReloadMaintainWorkDataEvent(mRepairId));
            }
        });
    }

    @Override
    public void checkPassSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                EventBus.getDefault().post(new ReloadBusNumberDataEvent());
            }
        });
    }

    @Override
    public void cancelWorkSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                EventBus.getDefault().post(new ReloadBusNumberDataEvent());
            }
        });
    }

    @OnClick(R2.id.tv_check_not_pass)
    public void onNotPass() {

        new DialogFinishNotPass(_mActivity, "竣检不通过",
                mClassificationAdapter.getData(),
                new DialogFinishNotPass.OnConfirmListener() {
                    @Override
                    public void onConfirm(String ids, String reason) {
                        mDialogLoader.showProgressDialog(true, "正在提交", "请稍候...");
                        mPresenter.checkPass(UserManager.getInstance().getToken(),
                                mRepairId, ids, reason, 1
                        );
                    }
                }).measureSize().show();
    }

    @OnClick(R2.id.tv_check_pass)
    public void onPass() {
        if (!mCbProtocol.isChecked()) {
            ToastUtils.showShort("请先确认竣检标准!");
        } else {
            mDialogLoader.showProgressDialog(true, "正在提交", "请稍候...");
            mPresenter.checkPass(UserManager.getInstance().getToken(), mRepairId, "",
                    "", 0);
        }

    }

    @OnClick(R2.id.tv_protocol)
    public void onProtocol() {
        DialogProtocol dialogProtocol = new DialogProtocol(_mActivity,
                UserManager.getInstance().getToken(),
                mRepairId,
                new OnItemChooseListener<Object>() {
                    @Override
                    public void onChoose(Object o) {
                        mCbProtocol.setChecked(true);
                    }
                });
        Window dialogWindow = dialogProtocol.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogProtocol.show();
        }
    }

    @OnClick(R2.id.tv_bus_info)
    public void onShowBusInfo() {
        EventBus.getDefault().post(new StartBrotherEvent(BusInfoDelegate.newInstance(mRepairId)));
    }

    @OnClick(R2.id.tv_cancel_work)
    public void onWorkCancel() {
        mDialogLoader.showProgressDialog(false, "正在提交", "请稍候...");
        mPresenter.cancelFinishWork(UserManager.getInstance().getToken(),
                mRepairId);
    }
}
